//保存表格的实例对象
var sx = null;

//调用封装方法
getTable();



// ---------------------------------------------------
//方法区

//封装方法重载表格
function sxTable(){
    //通过表格id参数  重载刷新
    sx.reload()
}


//封装渲染表格
function getTable(){
    layui.use(['table','layer','jquery','form','element'],function() {
        //模板保存到变量上
        var table = layui.table;
        var layer = layui.layer;
        var form = layui.form;
        var $ = layui.$;
        var element = layui.element;


        //监听顶部搜索按钮
        form.on('submit(ff)',function (d){
            console.log(d.field)
            var data = d.field;
            sx.reload({
                url:'/getCouponList',
                where:{
                    discountsName : data.discountsName,
                    discountsType : data.discountsType,
                    discountsQuantity : 1
                }
            },true)
            return false
        })


        sx = table.render({
            elem:"#demo",
            url:"/getCouponList",
            where:{
                discountsName:null,
                discountsType:null,
                discountsQuantity:1
            },
            page:{
                layout:['count','prev','page','next','limit'],
                groups:5,
                limit:10,
                limits:[5,10,20]
            },
            cols: [
                [
                    {checkbox:true},
                    {field: 'discountsId', title: '序号',width: 85,align: 'center'},
                    {field: 'discountsName', title: '优惠券名称',width: 120,align: 'center'},
                    //页面获取图片样子
                    {field: "discountsPicture", title: "优惠券图片",width:180,align: 'center', templet:function (d){
                            return '<img src="http://43.143.176.39/'+ d.discountsPicture +' " width="100px" height="100px" style="border-radius: 30px"; border="2 solid blue" > '
                    }},
                    {field: 'discountsType', title: '优惠卷类型',width: 150,align: 'center',templet: function (d){
                            if(d.discountsType == '商品'){
                                return '<i class="layui-icon layui-icon-component" style="font-size: 25px; color: #01AAED;"></i>  '
                            }else if(d.discountsType == '视频') {
                                return '<i class="layui-icon layui-icon-video" style="font-size: 25px; color: #01AAED;"></i>  '
                            }else{
                                return '<i class="layui-icon layui-icon-diamond" style="font-size: 25px; color: #01AAED;"></i>  '
                            }
                    }},
                    {field: 'discountsOriginal', title: '发行数量',width: 120,align: 'center'},
                    {field: 'discountsBegin', title: '优惠金额',width: 120,align: 'center',
                    templet:function (d){
                        return d.discountsBegin + '元'
                    }},
                    {field: 'bfb', title: '剩余数量',width: 300,align: 'center',
                    templet: function (d){
                        //***重点***：判断颜色
                        var ys = '';
                        if(30 < d.bfb && d.bfb < 100){
                            ys = 'layui-bg-orange'
                        }else if(0 < d.bfb && d.bfb <= 30){
                            ys = 'layui-bg-red'
                        }
                        //***重点***：拼接进度条
                        return '<div class="layui-progress layui-progress-big" lay-showpercent="true"><div class="layui-progress-bar '+ ys +'" lay-percent="'+ d.bfb +'%"></div></div>'
                    }},
                    // {field: 'discountsFinish', title: '开始时间',width: 180,align: 'center'},
                    // {field: 'discountsWire', title: '结束时间',width: 180,align: 'center'}
                ]
            ],
            toolbar:'#toolbardemo',
            skin: 'line',
            parseData:function (res){
                return{
                    "code": res.code,
                    "msg": res.msg,
                    "count": res.count,
                    "data": res.data
                }
            },
            done:function (res,currentCount) {
                //***重点***：table渲染完成后渲染element进度条
                element.render()
            }

        }),

        //监听表格头部
        table.on('toolbar(filterDemo)',function (obj){
            var event = obj.event
            var checkStatus = table.checkStatus(obj.config.id);
            var data =  checkStatus.data;
            // console.log(event)
            // console.log(checkStatus)
            // console.log(data)

            if (obj.event == 'add'){
                if (data.length == 0){
                    layer.msg('至少选择一张优惠劵进行发放',{icon:5,time:1000})
                }else {
                    var array = [];
                    $.each(data,function (){
                        // console.log(this)
                        array.push(this.discountsId)
                    })
                    var userArray = $('#userArray').val()
                    console.log('用户数组',userArray)
                    console.log('优惠卷数组',array.toString())
                    //发送ajax查询发放优惠劵数量是否足够
                    $.ajax({
                        type:'post',
                        url:'/getCouponNumById',
                        data:{
                            couponArray:array.toString(),
                            userArrayLength:userArray.length
                        },
                        dataType:'json',
                        success:function (res){
                            console.log(res)
                            if (res.data.length == 0){
                                //发送ajax为用户赠送优惠券
                                $.ajax({
                                    type:'get',
                                    url:'/YltUser/UserManage/couponIssuance',
                                    data:{
                                        userArray: userArray.toString(),
                                        couponArray:array.toString()
                                    },
                                    dataType:'json',
                                    success:function (res){
                                        console.log(res)
                                        if (res.state == '200'){
                                            //先得到当前iframe层的索引
                                            layer.msg("发放优惠券成功",{time: 1500,icon:6},function (){
                                                let index = parent.layer.getFrameIndex(window.name);
                                                //再执行关闭
                                                parent.layer.close(index);
                                                //调用自己写的重载方法
                                                parent.sxTable();
                                            })

                                        }else {
                                            layer.msg("发放优惠券失败",{time: 1500,icon:5},function (){
                                                let index = parent.layer.getFrameIndex(window.name);
                                                //再执行关闭
                                                parent.layer.close(index);
                                            });
                                        }
                                    }
                                })
                            }else {
                                layer.msg('编号为：' + res.data + ' 的优惠劵数量不足，请合理发放！',{time: 2000,icon:5})
                            }
                        }
                    })
                }
            }
        })
    })
}
